<template>
  <div>
    <page-tools>
      <template #left>
        <div class="tips">
          <i class="el-icon-info" />
          <span>本月: 社保在缴 公积金在缴</span>
        </div>
      </template>
      <template #right>
        <!-- 右侧 -->
        <el-button type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
        <el-button type="danger" size="small" @click="handleDownload">excel导出</el-button>
        <el-button type="primary" size="small" @click="addEmployee">新增员工</el-button>
      </template>
    </page-tools>

    <!-- 卡片 -->
    <el-card style="margin-top: 10px;">
      <el-table border :data="list">
        <el-table-column width="60" label="序号" type="index" />
        <el-table-column label="姓名" prop="username" />
        <el-table-column label="头像" width="110">
          <!-- 头像 -->
          <template #default="scope">
            <!-- <img :src="scope.row.staffPhoto" alt="" width="80"> -->
            <el-image :src="scope.row.staffPhoto" class="avatar">
              <!-- 具名插槽新语法  图片加载出错的时候自动显示 -->
              <template #error>
                <!-- <i class="el-icon-picture-outline" /> -->
                <img src="@/assets/common/bigUserHeader.png" width="80">
              </template>
            </el-image>
          </template>
        </el-table-column>

        <el-table-column label="工号" prop="workNumber" />
        <el-table-column label="聘用形式">
          <template #default="{row}">
            {{ formatEmployee(row.formOfEmployment) }}
          </template>
        </el-table-column>
        <el-table-column label="部门" prop="departmentName" />
        <el-table-column label="入职时间">
          <template #default="{row}">
            {{ formatTime(row.timeOfEntry) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="{row}">
            <el-button type="text" size="small" @click="goDetail(row.id)">查看</el-button>
            <el-button type="text" size="small" @click="assignRole(row.id)">分配角色</el-button>
            <el-button type="text" size="small" @click="DelEmploy(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div style="height: 60px; margin-top: 10px">
        <el-pagination
          :total="total"
          :current-page="params.page"
          :page-size="params.size"
          layout="prev, pager, next"
          @current-change="pageChange"
        />
      </div>
    </el-card>
    <!-- 弹出层 -->
    <add-employee :visible="dialogVisible" @close-dialog="closeDialog" />

    <!-- 给员工分配角色弹出层 -->
    <el-dialog class="assign-role" title="分配角色" :visible="showRoleDialog" @close="closeRoleDialog" @open="openRoleDialog">

      <!-- 这里准备复选框 -->
      <el-checkbox-group v-model="checkList">
        <el-checkbox
          v-for="item in roleList"
          :key="item.id"
          :label="item.id"
        >
          {{ item.name }}
        </el-checkbox>
      </el-checkbox-group>

      <template #footer>
        <el-button type="primary" size="small" @click="confirmAssgin">确定</el-button>
        <el-button size="small" @click="closeRoleDialog">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script>
// 导入组件
// import PageTools from '@/components/PageTools/index'
import { getEmployeeList, delEmployee, fetchAssignRole } from '@/api/employees.js'
import dayjs from 'dayjs'
import AddEmployee from '@/views/Employee/component/add-employee'
import { getExportData } from '@/utils/excel'
import { getRoleList } from '@/api/setting.js'
import { getUserDetailById } from '@/api/user'
export default {

  // 注册组件
  components: {
    AddEmployee
  },
  data() {
    return {
      list: [],
      params: {
        page: 1,
        size: 10
      },
      total: 0,
      dialogVisible: false,
      showRoleDialog: false,

      // 当前已分配的角色
      roleList: [],
      checkList: [], // 所有选中项的角色id组成的数组
      curId: null // 暂存的当前项的id
    }
  },
  mounted() {
    this.fetchList()
  },
  methods: {
    // 获取列表
    async fetchList() {
      const { rows, total } = await getEmployeeList(this.params)
      this.list = rows
      this.total = total
    },
    formatEmployee(type) {
      // 前端枚举优化: 先把所有的对应关系通过对象定义出来 + 对象的取值 -> 策略模式 优化多分支语句的
      const MAP = {
        1: '正式',
        2: '非正式',
        4: '其他'
      }
      return MAP[type]
    },
    // 格式化时间格式
    formatTime(time) {
      return dayjs(time).format('YYYY-MM-DD')
    },
    // 页面改变
    pageChange(page) {
      this.params.page = page
      // 更新列表
      this.fetchList()
    },
    // 删除员工
    async DelEmploy(id) {
      this.$confirm('你确认要删除该员工吗?', '温馨提示').then(async() => {
        await delEmployee(id)
        // 更新列表
        this.fetchList()
        this.$message.success('删除员工成功')
      }).catch(error => {
        console.log(error)
      })
    },
    // 添加员工
    addEmployee() {
      this.dialogVisible = true
    },
    // 关闭弹框
    closeDialog() {
      this.dialogVisible = false
    },
    // 导出excel文件
    handleDownload() {
      // 只有使用它的时候才会出现动态加载     进行打包不会出现在打出的包里面  不会占用体积
      import('@/vendor/Export2Excel').then(async excel => {
        // excel表示导入的模块对象

        // 获取当页数据
        const res = await getEmployeeList(this.params)
        // 表头数据格式
        const headerRelation = {
          '姓名': 'username',
          '手机号': 'mobile',
          '入职日期': 'timeOfEntry',
          '工号': 'workNumber',
          '聘用形式': 'formOfEmployment',
          '部门': 'departmentName'
        }
        // 转换员工聘用形式数据为中文
        const { data } = getExportData(res.rows, headerRelation)
        excel.export_json_to_excel({
          header: [...Object.keys(headerRelation)], // 表头header 必填 要求是一个数组
          data: data, // 表格数据body 要求是一个二维数组
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    // 跳转至修改页面   并将当前查看项的id传过去
    goDetail(id) {
      this.$router.push({
        path: '/detail',
        query: {
          id
        }
      })
    },
    assignRole(id) {
      this.showRoleDialog = true
      this.curId = id
    },
    async openRoleDialog() {
      const res = await getRoleList({
        page: 1,
        pagesize: 100
      })
      this.roleList = res.rows

      // 获取已选角色
      const detail = await getUserDetailById(this.curId)
      // 回显
      this.checkList = detail.roleIds
    },
    closeRoleDialog() {
      this.showRoleDialog = false
    },
    // 提交选择角色
    async confirmAssgin() {
      await fetchAssignRole({
        id: this.curId,
        roleIds: this.checkList
      })
      this.$message.success('分配角色成功')
      this.closeRoleDialog()
    }
  }
}
</script>
<style >
/* 图片上传进度条样式 */
.avatar {
  position: absolute;
  display: flex;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  background: #fff;
}
</style>
